package domainofratingsindexer;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;



/**
 * @author Martin Mihalovic
 */
public class DataAccess {    
    private Connection connection;
    
    DataAccess() throws SQLException {        
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/porada3", "root", "sestica003");      //Shame :(
    }
    
    
    /**
     * Get list of all domain IDs that have at least one rating
     */
    List<String> GainDomains() throws SQLException {
        List<String> result = new ArrayList<String>();
        ResultSet set = doQuery("SELECT DISTINCT domainID FROM rating;");
        
        while(set.next())
            result.add(set.getString("domainID"));

        set.close();
        return result;
    }
    
    
    List<UserRating> GainPositiveRatingsInDomain(String domainId) throws SQLException {
        List<UserRating> result = new ArrayList<UserRating>();
        ResultSet set = doQuery("SELECT ratingID, domainID FROM rating WHERE weight>0.0 AND domainID='" + domainId + "'");
        
        while(set.next()) {
            UserRating rating = new UserRating();
            rating.RatingId = set.getInt("ratingID");
            rating.DomainId = set.getString("domainID");       //Actually not much usefull
            
            result.add(rating);
        }
        
        return result;
    }
    
    
    private ResultSet doQuery(String query) throws SQLException {
        Statement statement;

        statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        return statement.executeQuery(query);
    }
    
    
    
    protected void finalize() throws SQLException {
        connection.close();
    }
}
